package com.base.hong.widget

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.util.AttributeSet
import android.view.View
import java.lang.Math.cos
import kotlin.math.atan2
import kotlin.math.pow
import kotlin.math.sin
import kotlin.math.sqrt

class PieChartView(context: Context, attrs: AttributeSet) : View(context, attrs) {

    // 饼状图数据
    private var pieData: List<PieData>? = null

    // 饼状图颜色
    private var pieColors: IntArray = intArrayOf(
        Color.parseColor("#FFC300"),
        Color.parseColor("#FF5733"),
        Color.parseColor("#C70039"),
        Color.parseColor("#900C3F"),
        Color.parseColor("#581845")
    )

    // 中心文本
    private var centerText: String = ""

    // 动画
    private var animator: ValueAnimator? = null
    private var selectedPieIndex: Int = -1
    private var selectedPieCenterX: Float = 0f
    private var selectedPieCenterY: Float = 0f

    // 画笔
    private val paint = Paint()

    // 画布宽高
    private var canvasWidth: Float = 0f
    private var canvasHeight: Float = 0f

    // 饼状图属性
    private val pieRadius: Float by lazy { canvasWidth / 4f }
    private val pieCenterX: Float by lazy { canvasWidth / 2f }
    private val pieCenterY: Float by lazy { canvasHeight / 2f }
    private val startAngle: Float = -90f

    init {
        paint.isAntiAlias = true
        paint.style = Paint.Style.FILL

        animator = ValueAnimator.ofInt(0, 360).apply {
            duration = 300
            addUpdateListener { invalidate() }
        }

        setOnClickListener {
            val index = getClickPieIndex(it.x, it.y)
            if (index != -1) {
                selectedPieIndex = index
                val pieData = pieData!![selectedPieIndex]
                val sweepAngle = 360 * pieData.percent
                val middleAngle = startAngle + sweepAngle / 2
                selectedPieCenterX = pieCenterX + pieRadius * cos(Math.toRadians(middleAngle.toDouble())).toFloat()
                selectedPieCenterY = pieCenterY + pieRadius * sin(Math.toRadians(middleAngle.toDouble())).toFloat()
                animator?.start()
            } else {
                selectedPieIndex = -1
                animator?.reverse()
            }
        }
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        canvasWidth = measuredWidth.toFloat()
        canvasHeight = measuredHeight.toFloat()
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)

        pieData?.let {
            var startAngle = this.startAngle

            for ((index, data) in it.withIndex()) {
                // 绘制扇形
                paint.color = pieColors[index % pieColors.size]
                val sweepAngle = 360 * data.percent
                if (index == selectedPieIndex) {
                    canvas?.save()
                    canvas?.translate(selectedPieCenterX - pieCenterX, selectedPieCenterY - pieCenterY)
                    canvas?.drawArc(
                        RectF(
                            pieCenterX - pieRadius * 1.2f,
                            pieCenterY - pieRadius * 1.2f,
                            pieCenterX + pieRadius * 1.2f,
                            pieCenterY + pieRadius * 1.2f
                        ),
                        startAngle,
                        sweepAngle,
                        true,

                        paint
                    )
                    canvas?.restore()
                } else {
                    canvas?.drawArc(
                        RectF(
                            pieCenterX - pieRadius,
                            pieCenterY - pieRadius,
                            pieCenterX + pieRadius,
                            pieCenterY + pieRadius
                        ),
                        startAngle,
                        sweepAngle,
                        true,
                        paint
                    )
                }

                // 绘制中心文本
                if (selectedPieIndex == -1 && !centerText.isNullOrEmpty()) {
                    paint.color = Color.BLACK
                    paint.textSize = pieRadius / 2
                    paint.textAlign = Paint.Align.CENTER
                    val textX = pieCenterX
                    val textY = pieCenterY - (paint.ascent() + paint.descent()) / 2
                    canvas?.drawText(centerText, textX, textY, paint)
                }

                // 更新起始角度
                startAngle += sweepAngle
            }

            // 绘制选中的扇形的中心文本
            if (selectedPieIndex != -1) {
                paint.color = Color.WHITE
                paint.textSize = pieRadius / 2
                paint.textAlign = Paint.Align.CENTER
                val pieData = it[selectedPieIndex]
                val textX = selectedPieCenterX
                val textY = selectedPieCenterY - (paint.ascent() + paint.descent()) / 2
                canvas?.drawText("${pieData.name}\n${(pieData.percent * 100).toInt()}%", textX, textY, paint)
            }
        }
    }

    /**
     * 设置饼状图数据
     */
    fun setPieData(data: List<PieData>) {
        this.pieData = data
        invalidate()
    }

    /**
     * 设置中心文本
     */
    fun setCenterText(text: String) {
        this.centerText = text
        invalidate()
    }

    /**
     * 获取点击的扇形的索引
     */
    private fun getClickPieIndex(x: Float, y: Float): Int {
        if (pieData == null) {
            return -1
        }

        // 判断是否在饼状图内部
        val distance = sqrt((x - pieCenterX).pow(2) + (y - pieCenterY).pow(2))
        if (distance > pieRadius) {
            return -1
        }

        // 判断点击的是哪个扇形
        val clickAngle = atan2(y - pieCenterY, x - pieCenterX) / Math.PI * 180
        var startAngle = this.startAngle
        for ((index, data) in pieData!!.withIndex()) {
            val sweepAngle = 360 * data.percent
            if (clickAngle >= startAngle && clickAngle <= (startAngle + sweepAngle)) {
                return index
            }
            startAngle += sweepAngle
        }
        return -1
    }
}
/**
 * 饼状图数据类
 */
data class PieData(val name: String, val percent: Float)